#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include "trapezoidal.h"


/* To find the integration accurately split the intervals of the integration into n intervals and find out summation of it. 
   And then apply trapeziodal rule on it */
double calc_sum(FnP fnPtr, double lo_bound, double hi_bound, int n_intervals){
  int k;
  double sum_result = 0;

  for (k = 1; k <= (n_intervals - 1); k++){
    sum_result = sum_result + fnPtr(lo_bound + k * (hi_bound - lo_bound) / n_intervals); 
  }
  return sum_result;
}

/* Funtion for calulating integral by using trapezoidal rule */
double trapezoidal(FnP fnPtr, double lo_bound, double hi_bound, int n_intervals){
  
	//char buf[512] = "";
  double trapezoidal_result;	/* Store trapezoidal result */
  double sum_result;		/* Store summation result */

  /*Calculate the summation */
  sum_result = calc_sum (fnPtr, lo_bound, hi_bound, n_intervals);

	//sprintf (buf, "Data :  %lf %lf %d\n", lo_bound, hi_bound, n_intervals);
  //fprintf (stderr, "%s\n",buf);
	/*Compute actual trapezoidal result */
  trapezoidal_result = ((hi_bound - lo_bound) / n_intervals) * ( (fnPtr(hi_bound) + fnPtr(lo_bound))/2 + sum_result);
  return trapezoidal_result;
}

#ifdef TRAPEZOIDAL_TEST

int main (void){
  double result;
  result = trapezoidal(fns[0].f, 10, 20, 4);
  printf ("TRAPEZIODAL-TEST Result: %.6g\n", result);
  return 0;
}
#endif


